import pool from '@/server/db'
import joi from 'joi'
import md5 from 'md5'
import { RowDataPacket } from 'mysql2'
import r from '@/server/utils/r'
import jwt from 'jsonwebtoken'

const schema = joi.object({
  phone: joi.string().pattern(/1\d{10}/),
  password: joi.string().required(),
})

export default defineEventHandler(async event => {
  const body = await readBody(event)
  let users = []
  // 数据验证
  try {
    const value = await schema.validateAsync(body)
  } catch (err) {
    return r('数据验证错误：' + err)
  }
  // 验证手机号是否注册，密码是否正确
  try {
    const salt = 'sqfqsffr0'
    const password = md5(md5(body.password) + salt)
    const [result] = await pool.execute(
      'SELECT * FROM `users` WHERE `phone`=?',
      [body.phone]
    )

    if (
      (result as RowDataPacket[]).length === 0 ||
      (result as RowDataPacket[])[0].password !== password
    )
      return r('账号或密码输入错误')

    users = result as RowDataPacket[]
  } catch (err) {
    return r('手机号或密码验证错误：' + err)
  }
  // 生成token
  try {
    const { jwtSecret } = useRuntimeConfig(event)
    const token =
      `Bearer ` +
      jwt.sign({ uid: users[0].id }, jwtSecret, {
        expiresIn: '10 days',
      })
    const userinfo = Object.fromEntries(
      Object.entries(users[0]).filter(([key]) => key !== 'password')
    )
    return r('登录成功', 1, { token, userinfo })
  } catch (error) {
    return r('token 生成失败：' + error)
  }
})
